package com.gx.smart.building.ui.assets.adapter;

import android.util.SparseArray;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaosy
 * @create 2020/7/7
 * @Describe
 **/
public class PageAdapter extends FragmentStateAdapter {
    private int index = 0;
    private final SparseArray<Fragment> list = new SparseArray<>();
    private final List<Long> pageIds = new ArrayList<>();

    public PageAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    public void add(Fragment fragment) {
        list.put(index, fragment);
        pageIds.add((long) fragment.hashCode());
        index++;
        notifyItemInserted(index);
    }

    public void clear() {
        index = 0;
        list.clear();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if (list.size() == 0) {
            return null;
        }
        return list.get(position);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public long getItemId(int position) {
        return list.get(position).hashCode();
    }

    @Override
    public boolean containsItem(long itemId) {
        return pageIds.contains(itemId);
    }
}
